<template>
  <div>
    <a-input-search
      v-model="selectedOrderNos"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch"
    >
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item label="订单编号">
                  <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="客户名称">
                  <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="工程名称">
                  <a-input placeholder="请输入工程名称" v-model="queryParam.projectName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            type: multiple ? 'checkbox' : 'radio',
          }"
          :customRow="customRowClick"
          :scroll="{ x: 900 }"
          @change="handleTableChange"
        >
          <!-- 金额格式化 -->
          <template slot="moneySlot" slot-scope="text">
            <span v-if="text !== undefined && text !== null">{{
              Number(text).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 })
            }}</span>
            <span v-else>¥0.00</span>
          </template>

          <!-- 生产状态列 -->
          <template slot="productionStatusSlot" slot-scope="text">
            <a-tag :color="getProductionStatusColor(text)">
              {{ getProductionStatusText(text) }}
            </a-tag>
          </template>

          <!-- 包装完成状态列 -->
          <template slot="packagingStatusSlot" slot-scope="text">
            <a-tag :color="text ? 'green' : 'orange'">
              {{ text ? '已完成' : '未完成' }}
            </a-tag>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import { getAvailableOrdersForInbound } from '@/api/wms/finishedGoodsInbound'
export default {
  name: 'JSelectFinishedOrderModal',
  props: {
    value: {
      type: [String, Array],
      default: '',
    },
    placeholder: {
      type: String,
      default: '请选择已完成生产的订单',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    modalWidth: {
      type: Number,
      default: 1200,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '选择生产完成订单',
    },
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      selectedRowKeys: [],
      selectedOrderIds: [], // 保存选择的订单ID
      selectedOrderNos: '', // 保存选择的订单编号
      selectedOrders: [], // 保存选择的订单信息
      selectedRows: [], // 保存选择的订单信息

      // 查询条件
      queryParam: {
        orderNo: '',
        customerName: '',
        projectName: '',
      },

      // 数据源
      dataSource: [],

      // 表格列
      columns: [
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          width: 120,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '工程名称',
          dataIndex: 'projectName',
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '下单日期',
          dataIndex: 'orderDate',
          width: 100,
          align: 'center',
        },
        {
          title: '交付日期',
          dataIndex: 'deliveryDate',
          width: 100,
          align: 'center',
        },
      ],

      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },

      loading: false,
      url: {
        list: '/wms/finished-goods-inbound/available-tasks', // 获取可入库的订单列表
        getOrdersByIds: '/oms/productSalesOrder/getOrdersByIds',
      },
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initSelectedOrders(val)
        } else {
          this.selectedOrderIds = []
          this.selectedOrderNos = ''
          this.selectedRowKeys = []
          this.selectedRows = []
          this.dataSource = []
          this.ipagination.current = 1
          this.ipagination.total = 0
        }
      },
    },
  },
  created() {
    this.searchReset()
  },
  methods: {
    // 获取生产状态文本
    getProductionStatusText(status) {
      switch (parseInt(status)) {
        case 0:
          return '未开始'
        case 1:
          return '生产中'
        case 2:
          return '已完成'
        case 3:
          return '已暂停'
        default:
          return '未知状态'
      }
    },

    // 获取生产状态颜色
    getProductionStatusColor(status) {
      switch (parseInt(status)) {
        case 0:
          return 'default'
        case 1:
          return 'blue'
        case 2:
          return 'green'
        case 3:
          return 'orange'
        default:
          return 'default'
      }
    },

    // 自定义行点击事件
    customRowClick(record) {
      return {
        onClick: () => {
          this.handleRowClick(record)
        },
      }
    },

    // 初始化已选择的订单信息
    initSelectedOrders(selectedIds) {
      if (!selectedIds) return

      // 处理不同类型的输入值
      let ids = selectedIds
      if (Array.isArray(selectedIds)) {
        ids = selectedIds.join(',')
      }
      if (!ids) return

      this.loading = true
      let params = { ids: ids }

      getAction(this.url.getOrdersByIds, params)
        .then((res) => {
          if (res.success) {
            this.selectedOrders = res.result || []
            this.selectedOrderIds = this.selectedOrders.map((item) => item.id)
            this.selectedOrderNos = this.selectedOrders.map((item) => item.orderNo).join(',')
            this.selectedRowKeys = this.selectedOrderIds
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 打开选择框
    handleSearch() {
      if (this.disabled) return

      this.visible = true
      this.loadData(1)
    },

    // 加载数据 - 只加载包装工种已完成的订单
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }

      this.loading = true

      // 调用MES模块的接口获取可入库订单
      getAction('mes/plan/finished-orders')
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result || []
            this.ipagination.total = this.dataSource.length
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取查询参数
    getQueryParams() {
      const param = Object.assign({}, this.queryParam)
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return param
    },

    // 选择改变
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

      if (!this.multiple) {
        this.selectedOrders = selectedRows
      } else {
        // 保持已经选择的和当前页面选择的
        const selectedIds = selectedRows.map((row) => row.id)
        this.selectedOrders = this.selectedOrders.filter((item) => {
          return selectedIds.includes(item.id) || !this.dataSource.map((row) => row.id).includes(item.id)
        })

        // 添加当前页面新选择的
        selectedRows.forEach((row) => {
          const exist = this.selectedOrders.some((item) => item.id === row.id)
          if (!exist) {
            this.selectedOrders.push(row)
          }
        })
      }
    },

    // 查询按钮
    searchQuery() {
      this.loadData(1)
    },

    // 重置按钮
    searchReset() {
      this.queryParam = {
        orderNo: '',
        customerName: '',
        projectName: '',
      }
      this.loadData(1)
    },

    // 表格分页、排序、筛选变化
    handleTableChange(pagination, filters, sorter) {
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      this.loadData()
    },

    // 处理行点击事件
    handleRowClick(record) {
      // 获取当前行的key
      const rowKey = record.id

      // 根据是否多选处理不同的逻辑
      if (!this.multiple) {
        // 单选模式：直接设置当前行为选中状态
        this.selectedRowKeys = [rowKey]
        this.selectedOrders = [record]
      } else {
        // 多选模式：切换选中状态
        const index = this.selectedRowKeys.indexOf(rowKey)
        if (index === -1) {
          // 如果未选中，则添加到选中列表
          this.selectedRowKeys.push(rowKey)

          // 检查记录是否已存在于selectedOrders中
          const exist = this.selectedOrders.some((item) => item.id === record.id)
          if (!exist) {
            this.selectedOrders.push(record)
          }
        } else {
          // 如果已选中，则从选中列表移除
          this.selectedRowKeys.splice(index, 1)

          // 从selectedOrders中移除
          const orderIndex = this.selectedOrders.findIndex((item) => item.id === record.id)
          if (orderIndex !== -1) {
            this.selectedOrders.splice(orderIndex, 1)
          }
        }
      }
    },

    // 确定按钮
    handleOk() {
      this.selectedOrderIds = this.selectedOrders.map((item) => item.id)
      this.selectedOrderNos = this.selectedOrders.map((item) => item.orderNo).join(',')

      this.$emit('input', this.selectedOrderIds.join(','))
      this.$emit('change', this.selectedOrders)

      this.handleCancel()
    },

    // 取消按钮
    handleCancel() {
      this.visible = false
    },
  },
}
</script>

<style scoped>
.query-area {
  margin-bottom: 16px;
}

/* 添加鼠标悬停样式，提升用户体验 */
:deep(.ant-table-tbody > tr) {
  cursor: pointer;
}

:deep(.ant-table-tbody > tr:hover) {
  background-color: #e6f7ff;
}

/* 表格样式优化 */
.ant-table-bordered .ant-table-thead > tr > th,
.ant-table-bordered .ant-table-tbody > tr > td {
  padding: 12px 8px;
}

/* 金额列右对齐 */
.ant-table-tbody > tr > td.ant-table-column-money {
  text-align: right !important;
}
</style>
